package com.adgox.tiantianbiting.music;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.Messenger;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.adgox.tiantianbiting.R;
import com.adgox.tiantianbiting.bean.BaseResponseBean;
import com.adgox.tiantianbiting.bean.PageBean;
import com.adgox.tiantianbiting.bean.ProgramChooseBean;
import com.adgox.tiantianbiting.bean.UserInfo;
import com.adgox.tiantianbiting.home.programDetail.ProgramDetailActivity;
import com.adgox.tiantianbiting.main.MainActivity;
import com.adgox.tiantianbiting.net.callback.JsonCallback;
import com.adgox.tiantianbiting.utils.ApiConstant;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.rae.swift.session.SessionManager;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashSet;
import java.util.Set;

public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {

    private MediaPlayer mediaPlayer;
    private int mediaState;

    private static final int MEDIA_STATE_PLAY = 1;
    private static final int MEDIA_STATE_PAUSE = 2;
    private static final int MEDIA_STATE_STOP = 3;
    private Messenger messenger;
    private int duration;
    private int currentPosition;
    private int programId;
    private int clickPosition;
    private String img;

    private int NOTIFACATION_ID = 123;
    private Notification notification;
    private RemoteViews contentViews;
    private String CHANNEL_ID = "ttbt_channel";
    private String CHANNEL_NAME = "ttbt_name";
    private RemoteViews miniContentViews;
    private String name;
    private Bitmap bitmap;
    private NotificationCompat.Builder mBuilder;
    private PlayReceiver playReceiver;
    private int NOTIFICATION_CODE = 110;
    private int seasonId;

    public MusicService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        throw new UnsupportedOperationException("Not yet implemented");
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnPreparedListener(this);
        playReceiver = new PlayReceiver();
        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction("play");
        mFilter.addAction("pause");
        mFilter.addAction("last");
        mFilter.addAction("next");
        registerReceiver(playReceiver, mFilter);
    }


    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        if (intent == null) return super.onStartCommand(intent, flags, startId);;
        String option = intent.getStringExtra("option");
        if (messenger == null) {
            messenger = (Messenger) intent.getExtras().get("messenger");
        }
        //play按钮的点击
        if ("play".equals(option)) {
            if (mediaState == MEDIA_STATE_PLAY) {
                //当前状态是播放那就暂停
                pause();
            } else if (mediaState == MEDIA_STATE_PAUSE) {
                //当前状态是暂停那就继续播放
                continuePlay();
            } else {
                //都不是的话，那就是新节目刚开始;当前时长和总时长清零
                currentPosition = 0;
                duration = 0;
                programId = intent.getIntExtra("programId", -1);
                seasonId = intent.getIntExtra("seasonId", -1);
                clickPosition = intent.getIntExtra("clickPosition", -1);
                img = intent.getStringExtra("img");
                name = intent.getStringExtra("name");
                mediaState = MEDIA_STATE_PLAY;
                Glide.with(this).load(img).asBitmap().into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        bitmap = resource;
                        //设为前台service，防杀死
//                        initNotificationMini();
//                        initNoti();
//                        initNotification();
                        start(intent.getStringExtra("path"));
                    }
                });

            }
        } else if ("seekPlay".equals(option)) {
            //如果是拖动进度条跳转，那就直接seekto到相应的节点
            currentPosition = intent.getIntExtra("progress", -1);
            if (currentPosition >= 0) {
                mediaPlayer.seekTo(currentPosition);
            }
        } else if ("reattach".equals(option)) {
            //activity重新启动，发送最新状态给它
            Intent sIntent = new Intent();
            sIntent.putExtra("playStatus", "reattach");
            sIntent.putExtra("isPlaying", mediaPlayer.isPlaying());
            sIntent.putExtra("duration", duration);
            sIntent.putExtra("programId", programId);
            sIntent.putExtra("seasonId", seasonId);
            sIntent.putExtra("clickPosition", clickPosition);
            sIntent.setAction("com.adgox.tiantianbiting.music.MusicService");
            sendBroadcast(sIntent);
        } else if ("kill".equals(option)) {
            //杀死当前的播放节目，本来想用stopself，结果重启后就无法找到相应service，所以就改成reset mediaplayer了。
            mediaPlayer.reset();
            mediaState = 0;
            handler.removeCallbacks(runnable);
        } else if ("choose".equals(option)) {
            //选集，相当于播放新集
            currentPosition = 0;
            duration = 0;
            programId = intent.getIntExtra("programId", -1);
            seasonId = intent.getIntExtra("seasonId", -1);
            clickPosition = intent.getIntExtra("clickPosition", -1);
            img = intent.getStringExtra("img");
            name = intent.getStringExtra("name");
            mediaState = MEDIA_STATE_PLAY;
            Glide.with(this).load(img).asBitmap().into(new SimpleTarget<Bitmap>() {
                @Override
                public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                    bitmap = resource;
                    start(intent.getStringExtra("path"));
                }
            });


        } else if ("home".equals(option)) {
            //首页转圈图片
            sendHomeIntent();
        } else if ("pause".equals(option)) {
            //定时暂停
            pause();
            sendHomeIntent();
        }

        return super.onStartCommand(intent, flags, startId);
    }

    public void sendHomeIntent() {
        Intent homeIntent = new Intent();
        homeIntent.putExtra("img", img);
        homeIntent.putExtra("programId", programId);
        homeIntent.putExtra("status", mediaState);
        homeIntent.setAction("com.adgox.tiantianbiting.music.MusicService2");
        sendBroadcast(homeIntent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(playReceiver);
        stopForeground(true);
    }

    public void start(String path) {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepareAsync();
            mediaPlayer.start();
            mediaState = MEDIA_STATE_PLAY;
            Intent intent = new Intent();
            intent.putExtra("playStatus", "play");
            intent.setAction("com.adgox.tiantianbiting.music.MusicService");
            sendBroadcast(intent);
            handler.removeCallbacks(runnable);
            handler.postDelayed(runnable, 500);
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "资源错误", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }

    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            mediaState = MEDIA_STATE_PAUSE;
            Intent intent = new Intent();
            intent.putExtra("playStatus", "pause");
            intent.setAction("com.adgox.tiantianbiting.music.MusicService");
            sendBroadcast(intent);
        }
    }

    public void continuePlay() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            mediaState = MEDIA_STATE_PLAY;
            Intent intent = new Intent();
            intent.putExtra("playStatus", "continue");
            intent.setAction("com.adgox.tiantianbiting.music.MusicService");
            sendBroadcast(intent);
        }
    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        duration = mediaPlayer.getDuration();
        //如果有本地播放进度记录，则直接跳转
        SharedPreferences playRecord = getSharedPreferences("playRecord_" + programId, MODE_PRIVATE);
        if (playRecord.getInt("seasonId", 0) == seasonId && playRecord.getInt("currentPosition", 0) != 0) {
            currentPosition = playRecord.getInt("currentPosition", 0);
            mediaPlayer.seekTo(playRecord.getInt("currentPosition", 0));
        }
        mediaPlayer.start();
        mediaState = MEDIA_STATE_PLAY;
        Intent intent = new Intent();
        intent.putExtra("playStatus", "play");
        intent.putExtra("duration", duration);
        intent.setAction("com.adgox.tiantianbiting.music.MusicService");
        sendBroadcast(intent);

        //记录播放内容,首页播放旋转图标要用到
        SharedPreferences sp = getSharedPreferences("ivplay", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("img", img);
        editor.putInt("programId", programId);
        editor.commit();

        initNotificationMini();
    }

//    private void initNoti() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
//            channel.setSound(null, null);
//            mBuilder = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID);
//        } else {
//            mBuilder = new NotificationCompat.Builder(getApplicationContext());
//        }
//        Intent noIntent = new Intent(getApplicationContext(), ProgramDetailActivity.class);
//        noIntent.putExtra("programId", programId);
//        noIntent.putExtra("programName", name);
//
//
//        contentViews = new RemoteViews(getPackageName(), R.layout.layout_music_player);
//        contentViews.setTextViewText(R.id.tv_book_name, name);
//        contentViews.setImageViewBitmap(R.id.img_book, bitmap);
//        contentViews.setTextViewText(R.id.tv_season_num, "第" + (clickPosition + 1) + "集");
//
//        mBuilder.setContent(contentViews);
//
//        Notification notification = mBuilder.build();
//        notification.when = System.currentTimeMillis();
//        notification.flags = Notification.FLAG_AUTO_CANCEL;
//        notification.icon = R.drawable.ic_ttbt;
//        startForeground(110, notification);
//
//
//    }

    private void initNotificationMini() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(null, null);
            notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID).build();
            notificationManager.createNotificationChannel(channel);
        } else {
            notification = new Notification();
        }
        Intent notiIntent = new Intent(getApplicationContext(), ProgramDetailActivity.class);
        notiIntent.putExtra("programId", programId);
        notiIntent.putExtra("programName", name);
        notification.when = System.currentTimeMillis();
        notification.contentIntent = PendingIntent.getActivity(this, 0, notiIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.icon = R.drawable.ic_ttbt;
        contentViews = new RemoteViews(getPackageName(), R.layout.layout_music_player_mini);
        contentViews.setTextViewText(R.id.tv_book_name, name);
        contentViews.setImageViewBitmap(R.id.img_book, bitmap);
        contentViews.setTextViewText(R.id.tv_season_num, "第" + (clickPosition + 1) + "集");
        notification.contentView = contentViews;
        startForeground(111, notification);
    }

    private void initNotification() {
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            channel.setSound(null, null);
            notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID).build();
            notificationManager.createNotificationChannel(channel);
        } else {
            notification = new Notification();
        }
        Intent notiIntent = new Intent(getApplicationContext(), ProgramDetailActivity.class);
        notiIntent.putExtra("programId", programId);
        notiIntent.putExtra("programName", name);
        notification.when = System.currentTimeMillis();
        notification.contentIntent = PendingIntent.getActivity(this, 0, notiIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.flags = Notification.FLAG_AUTO_CANCEL;
        notification.icon = R.drawable.ic_ttbt;
        contentViews = new RemoteViews(getPackageName(), R.layout.layout_music_player);
        contentViews.setTextViewText(R.id.tv_book_name, name);
        contentViews.setImageViewBitmap(R.id.img_book, bitmap);
        contentViews.setTextViewText(R.id.tv_season_num, "第" + (clickPosition + 1) + "集");

        if (mediaState == MEDIA_STATE_PLAY) {
            contentViews.setImageViewResource(R.id.img_play, R.drawable.icon_delay);
            Intent intentPause = new Intent("pause");
            PendingIntent piPause = PendingIntent.getBroadcast(getApplicationContext(), 100, intentPause, PendingIntent.FLAG_CANCEL_CURRENT);
            contentViews.setOnClickPendingIntent(R.id.img_play, piPause);
        } else {
            contentViews.setImageViewResource(R.id.img_play, R.drawable.icon_play);
            Intent intentPlay = new Intent("play");
            PendingIntent piPlay = PendingIntent.getBroadcast(getApplicationContext(), 100, intentPlay, PendingIntent.FLAG_UPDATE_CURRENT);
            contentViews.setOnClickPendingIntent(R.id.img_play, piPlay);
        }

        Intent intentLast = new Intent("last");
        PendingIntent piLast = PendingIntent.getBroadcast(getApplicationContext(), 100, intentLast, PendingIntent.FLAG_UPDATE_CURRENT);
        contentViews.setOnClickPendingIntent(R.id.img_last, piLast);

        Intent intentNext = new Intent("next");
        PendingIntent piNext = PendingIntent.getBroadcast(getApplicationContext(), 100, intentNext, PendingIntent.FLAG_UPDATE_CURRENT);
        contentViews.setOnClickPendingIntent(R.id.img_next, piNext);

        miniContentViews = new RemoteViews(getPackageName(), R.layout.layout_music_player_mini);
        miniContentViews.setTextViewText(R.id.tv_book_name, name);
        miniContentViews.setImageViewBitmap(R.id.img_book, bitmap);
        miniContentViews.setTextViewText(R.id.tv_season_num, "第" + (clickPosition + 1) + "集");
        if (Build.VERSION.SDK_INT >= 16) {
            notification.bigContentView = contentViews;
        } else {
            notification.contentView = miniContentViews;
        }
        startForeground(110, notification);
    }

    class PlayReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Build.VERSION.SDK_INT >= 16) {
                switch (action) {
                    case "play":
                        mediaPlayer.start();
                        mediaState = MEDIA_STATE_PLAY;
                        initNotification();
                        break;
                    case "pause":
                        mediaPlayer.pause();
                        mediaState = MEDIA_STATE_PAUSE;
                        break;
                    case "last":
                        Toast.makeText(context, "last", Toast.LENGTH_SHORT).show();
                        if (clickPosition == 0) {
                            Toast.makeText(context, "已经是第一集啦", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        play(clickPosition - 1);
                        initNotification();
                        break;
                    case "next":
                        Toast.makeText(context, "next", Toast.LENGTH_SHORT).show();
                        play(clickPosition + 1);
                        break;
                }
            }
        }
    }

    private void play(final int position) {
        OkGo.<BaseResponseBean<PageBean<ProgramChooseBean>>>get(ApiConstant.BASE_URL + ApiConstant.GET_PROGRAM_CHOOSE_INFO + programId)
                .params("sort", 0)
                .params("userId", ((UserInfo) SessionManager.getDefault().getUser()).getId())
                .params("startPoint", position / 10 + 1)
                .params("maxPage", 10)
                .execute(new JsonCallback<BaseResponseBean<PageBean<ProgramChooseBean>>>() {
                    @Override
                    public void onSuccess(Response<BaseResponseBean<PageBean<ProgramChooseBean>>> response) {
                        if (!"0".equals(response.body().getCode()) || response.body().getData() == null) {
                            Toast.makeText(getApplicationContext(), "获取资源出错", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        if (position >= response.body().getData().getTotalResults() - 1) {
                            Toast.makeText(getApplicationContext(), "已经是最后一集啦！", Toast.LENGTH_SHORT).show();
                            return;
                        }
                        String playUrl = response.body().getData().getData().get(position).getPlayUrl();
                        clickPosition = position;
                        start(playUrl);
                        initNotification();
                    }
                });
    }

    Handler handler = new Handler();

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            currentPosition = mediaPlayer.getCurrentPosition();
            Intent intent = new Intent();
            intent.putExtra("serviceProgramId",programId);
            intent.putExtra("currentPosition", currentPosition);
            intent.setAction("com.adgox.tiantianbiting.music.MusicService");
            sendBroadcast(intent);

            SharedPreferences sp = getSharedPreferences("playRecord_" + programId, MODE_PRIVATE);
            SharedPreferences.Editor editor = sp.edit();
            if (currentPosition != 0) {
                editor.putInt("seasonId", seasonId);
                editor.putInt("currentPosition", currentPosition);
            }
            editor.commit();

            handler.postDelayed(runnable, 1000);
        }
    };

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {
        if (currentPosition == 0) return;
        mediaState = MEDIA_STATE_STOP;
        //播放结束
        handler.removeCallbacks(runnable);
        Intent intent = new Intent();
        intent.putExtra("playStatus", "end");
        intent.setAction("com.adgox.tiantianbiting.music.MusicService");
        sendBroadcast(intent);

        Intent homeIntent = new Intent();
        homeIntent.putExtra("img", img);
        homeIntent.putExtra("programId", programId);
        homeIntent.putExtra("status", mediaState);
        homeIntent.setAction("com.adgox.tiantianbiting.music.MusicService2");
        sendBroadcast(homeIntent);
    }
}
